package com.vedu.user.controller;

import com.diandian.constant.PlatformConstants;
import com.diandian.result.Result;
import com.diandian.util.BeanCopyUtil;
import com.vedu.constant.Constants;
import com.vedu.helper.MessageHelper;
import com.vedu.user.constants.UserConstants;
import com.vedu.user.entity.bo.UserBo;
import com.vedu.user.entity.vo.UserVo;
import com.vedu.user.request.LoginParam;
import com.vedu.user.request.RegisterParam;
import com.vedu.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * version: 1.0
 *
 * @author yuancheng.li [create on 2018/8/1 23:45 ]
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MessageHelper messageHelper;

    @PostMapping("/login")
    @ResponseBody
    public Result<UserVo> userLogin(HttpSession session, @RequestBody LoginParam loginParam) {

        Result<UserVo> result = new Result<>();

        UserBo userBo = userService.findUser(loginParam.getUserName(), loginParam.getPassword());
        if (userBo == null) {
            // 用户不存在
            result.modifyResult(UserConstants.FAILED_LOGIN_CODE, UserConstants.FAILED_LOGIN_MSG_KEY);
        } else {
            // 添加到session
            session.setAttribute(Constants.SESSION_KEY, userBo);
            result.modifyResult(PlatformConstants.SYSTEM_SUCCESS_CODE, UserConstants.SUCCESS_LOGIN__MSG_KEY);
            result.setResult(BeanCopyUtil.sourceToTarget(userBo, UserVo.class));
        }

        return messageHelper.resolveResultMsg(result);
    }

    @PostMapping("/logout")
    @ResponseBody
    public Result<UserVo> userLogout(HttpSession session) {

        Result<UserVo> result = new Result<>();

        session.removeAttribute(Constants.SESSION_KEY);

        result.setMsg(UserConstants.SUCCESS_LOGOUT_MSG_KEY);

        return result;
    }

    @PostMapping("/register")
    @ResponseBody
    public Result<UserVo> registerUser(@RequestBody RegisterParam registerParam) {

        Result<UserVo> result = new Result<>();

        boolean insertResult = userService.createUser(BeanCopyUtil.sourceToTarget(registerParam, UserBo.class));

        result.setCode(insertResult ? PlatformConstants.SYSTEM_SUCCESS_CODE : UserConstants.USER_CREATE_ERROR_CODE);
        result.setMsg(insertResult ? UserConstants.USER_CREATE_SUCCESS_MSG_KEY : UserConstants.USER_CREATE_ERROR_MSG_KEY);

        return result;
    }

}
